import createHandler from './request'
import {queryOne} from "./fake-db"
import {getLoggedUser, loginAndGiveToken} from "./auth"
import encrypt from "../utils/encrypt"

const login = createHandler(({uid, password}) => {
    const user = queryOne('user', 'uid', uid)
    if (!user) {
        return {
            code: 1001,
            msg: '用户不存在'
        }
    }
    if (user.password !== encrypt(password)) {
        return {
            code: 1002,
            msg: '密码错误'
        }
    }
    if (!user.enable) {
        return {
            code: 1003,
            msg: '账号已被停用，请联系系统管理员'
        }
    }
    const role = queryOne('role', 'id', user.role)
    if (!role) {
        return {
            code: 1004,
            msg: '角色不存在，请联系系统管理员'
        }
    }
    if (!role || !role.enable) {
        return {
            code: 1005,
            msg: '角色已被停用，请联系系统管理员'
        }
    }
    return {
        code: 0,
        data: loginAndGiveToken(user)
    }
})

const checkLogged = createHandler(() => {
    const curUser = getLoggedUser()
    if (!curUser || !curUser.enable) {
        return {
            code: 101,
            msg: '登录过期'
        }
    } else {
        return {
            code: 0
        }
    }
})

export {login, checkLogged}